package com.aynu.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author mj
 * @version 1.0
 * @date 2021/3/21 17:51
 */
@Configuration
public class FeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate requestTemplate) {
                System.out.println("feign远程调用之前执行RequestInterceptor.apply方法");
                //1、RequestAttributes拿到刚进来的请求
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                //获取请求信息
                if (requestAttributes!=null) {
                    HttpServletRequest request = requestAttributes.getRequest();//老请求

                    //获取cookie
                    String cookie = request.getHeader("Cookie");
                    //给新请求同步cookie
                    requestTemplate.header("Cookie", cookie);
                }
            }
        };
    }
}
